package com.lam.framework.security.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import com.lam.common.base.domain.LoginUser;
import com.lam.common.context.AuthTypeEnum;
import com.lam.common.context.TokenUtils;
import com.lam.common.exception.LamAuthenticationException;

/**
 * token过滤器 验证token有效性
 * 
 * @author lam
 */
@Component
public class AuthenticationTokenFilter extends OncePerRequestFilter {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	
	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)throws ServletException, IOException {
		
		LoginUser loginUser = TokenUtils.getLoginUser(request);
		if (loginUser != null) {
			AuthTypeEnum authType = TokenUtils.getAuthType(request);
			if(!authType.getAuthType().equals(loginUser.getAuthType())) {
				logger.error("token和请求地址不匹配，token:{}, authType:{}", loginUser.getToken(), authType.getAuthType());
				throw new LamAuthenticationException("token和请求地址不匹配");
			}
			TokenUtils.refreshTokenExpires(loginUser);
		}
		chain.doFilter(request, response);
	}
}
